package com.laf.LAF.web;

import com.laf.LAF.domain.user.User;
import com.laf.LAF.domain.user.UserRepository;
import com.laf.LAF.exception.MessageException;
import com.laf.LAF.util.ValueCheck;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Controller
@Slf4j
public class RegisterController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/register")
    @SuppressWarnings("AssignmentToMethodParameter")
    @ApiOperation(value = "注册", notes = "")
    @ApiImplicitParam(name = "username", value = "用户名称", required = true, dataType = "User")
   /* @ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "User")
    @ApiImplicitParam(name = "rptPassword", value = "用户密码2", required = true, dataType = "User")*/
    public String register(
            HttpServletRequest request,
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("email") String email,
            @RequestParam("rptPassword") String rptPassword,
            @RequestParam("phone") String phone) {
        //contestOnlyService.checkRegister();
        ValueCheck.checkUserId(username);
        ValueCheck.checkPassword(password);
        ValueCheck.checkEmail(email);
        if (!Objects.equals(password, rptPassword)) {
            throw new MessageException("Passwords are not match");
        }
        if (StringUtils.hasText(username)) {
            username = username.trim();
        }

        if (userRepository.findByUsername(username) != null) {
            throw new MessageException("The ID( " + username + ") existed");
        }
     //   User user = new User();

        User user = User.builder().username(username)
                .password(password)
                .email(StringUtils.isEmpty(email) ? null : email)
                .phone(StringUtils.isEmpty(phone) ? null : phone)
                .build();
        userRepository.save(user);
        log.info("{}", user);
        request.setAttribute("user", user);
        return "register";
    }


    @GetMapping("/register")
    public String login(Model model) {

        return "register";
    }
}
